package com.flying.carclub;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.view.KeyEvent;
import android.view.inputmethod.InputMethodManager;
import android.widget.Toast;

/**
 * Created by zhuxiaocheng on 2018/1/15.
 */

public class BaseActivity extends AppCompatActivity {
    private AlertDialog mLoadingDialog;


    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (mLoadingDialog == null) {
            mLoadingDialog = new AlertDialog.Builder(this, R.style.dialog_transparent_no_fullscreen).create();
            mLoadingDialog.setCanceledOnTouchOutside(false);
            //使用该方法是避免有键盘的时候dialog不居中
            mLoadingDialog.show();
            mLoadingDialog.getWindow().setContentView(R.layout.common_mask);
            mLoadingDialog.dismiss();
        }
        if (mLoadingDialog != null) {
            mLoadingDialog.setOnKeyListener(new DialogInterface.OnKeyListener() {
                @Override
                public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
                    /*if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
                        BaseActivity.this.finish();
                        mLoadingDialog.dismiss();
                        BaseActivity.this.onKeyDown(keyCode, event);
                        return true;
                    }*/
                    return true;
                }
            });
        }
    }

    protected void showLoadingDialog() {
        if (!mLoadingDialog.isShowing()) {
            mLoadingDialog.show();
        }
    }

    protected void dismissLoadingDialog() {
        if (mLoadingDialog != null && mLoadingDialog.isShowing()) {
            mLoadingDialog.dismiss();
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (KeyEvent.KEYCODE_BACK == keyCode) {
            getWindow().getDecorView().clearAnimation();
            hideInputMethodWindows();
            finish();
            return true;
        } else {
            return super.onKeyDown(keyCode, event);
        }
    }

    protected void hideInputMethodWindows() {
        try {
            InputMethodManager imm = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
            imm.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), 0);
        } catch (Exception e) {
            // TODO: handle exception
            e.printStackTrace();
        }
    }

    protected void showToast(String msg){
        Toast.makeText(this, msg, Toast.LENGTH_SHORT).show();
    }
    protected void showToastLength(String msg){
        Toast.makeText(this, msg, Toast.LENGTH_LONG).show();
    }
}
